package com.ctsi.ssdc.service.impl;


import org.springframework.stereotype.Service;
import org.apache.commons.collections.CollectionUtils;
import com.ctsi.ssdc.domain.LitemallAftersale;
import com.ctsi.ssdc.domain.LitemallAftersaleExample;
import com.ctsi.ssdc.service.LitemallAftersaleService;
import com.ctsi.ssdc.repository.LitemallAftersaleRepository;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.Random;

import com.ctsi.ssdc.service.impl.StrengthenBaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import com.ctsi.ssdc.model.PageResult;
import org.springframework.data.domain.Pageable;
import com.github.pagehelper.PageHelper;

import static com.ctsi.ssdc.util.CharUtil.getRandomNum;

/**
 * Service Implementation for managing LitemallAftersale.
 *
 * @author ctsi-biyi-generator
 *
 */
@Service
public class LitemallAftersaleServiceImpl 
	extends StrengthenBaseServiceImpl<LitemallAftersaleRepository, LitemallAftersale, Integer, LitemallAftersaleExample> 
	implements LitemallAftersaleService {

    @Autowired
    LitemallAftersaleRepository litemallAftersaleRepository;


    /**
    * GET  /litemallAftersales : get the litemallAftersales firstStringBaseColumn.
    */
    @Override
    public PageResult<LitemallAftersale> findFirstStringColumn(String aftersaleSn,Pageable pageable){
        String str = aftersaleSn;
        if (Objects.nonNull(pageable)) {
            PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        }
        LitemallAftersaleExample litemallAftersaleExample = new LitemallAftersaleExample();
        String orderBy = getPageOrderBy(pageable);
        if(StringUtils.isNotEmpty(orderBy)) {
            litemallAftersaleExample.setOrderByClause(orderBy);
        }
        if (StringUtils.isEmpty(str)){
            litemallAftersaleExample.createCriteria();
        } else{
            litemallAftersaleExample.createCriteria().andAftersaleSnLike("%" + str +"%");
        }
        List<LitemallAftersale>  data = litemallAftersaleRepository.selectByExample(litemallAftersaleExample);

        long count = 0L;
        if (CollectionUtils.isNotEmpty(data)){
            count = litemallAftersaleRepository.countByExample(litemallAftersaleExample);
        }
        return new PageResult<LitemallAftersale>(data,count,count);
    }

    @Override
    public List<LitemallAftersale> queryList(Integer userId, Short status, Integer page, Integer limit, String sort, String order) {
        LitemallAftersaleExample example = new LitemallAftersaleExample();
        LitemallAftersaleExample.Criteria criteria = example.or();
        criteria.andUserIdEqualTo(userId);
        if (status != null) {
            criteria.andStatusEqualTo(status);
        }
        criteria.andDeletedEqualTo(false);
        if (!org.springframework.util.StringUtils.isEmpty(sort) && !org.springframework.util.StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        else{
            example.setOrderByClause(LitemallAftersale.Column.addTime.desc());
        }

        PageHelper.startPage(page, limit);
        return litemallAftersaleRepository.selectByExample(example);
    }

    @Override
    public LitemallAftersale findByOrderId(Integer userId, Integer orderId) {
        LitemallAftersaleExample example = new LitemallAftersaleExample();
        example.or().andOrderIdEqualTo(orderId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
        return litemallAftersaleRepository.selectOneByExample(example);
    }

    @Override
    public void deleteByOrderId(Integer userId, Integer orderId) {
        LitemallAftersaleExample example = new LitemallAftersaleExample();
        example.or().andOrderIdEqualTo(orderId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
        LitemallAftersale aftersale = new LitemallAftersale();
        aftersale.setUpdateTime(ZonedDateTime.now());
        aftersale.setDeleted(true);
        litemallAftersaleRepository.updateByExampleSelective(aftersale, example);
    }

    private String getRandomNum(Integer num) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


    public int countByAftersaleSn(Integer userId, String aftersaleSn) {
        LitemallAftersaleExample example = new LitemallAftersaleExample();
        example.or().andUserIdEqualTo(userId).andAftersaleSnEqualTo(aftersaleSn).andDeletedEqualTo(false);
        return (int) litemallAftersaleRepository.countByExample(example);
    }

    @Override
    public String generateAftersaleSn(Integer userId) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        String now = df.format(LocalDate.now());
        String aftersaleSn = now + getRandomNum(6);
        while (countByAftersaleSn(userId, aftersaleSn) != 0) {
            aftersaleSn = now + getRandomNum(6);
        }
        return aftersaleSn;
    }

    @Override
    public void add(LitemallAftersale aftersale) {
        aftersale.setAddTime(ZonedDateTime.now());
        aftersale.setUpdateTime(ZonedDateTime.now());
        litemallAftersaleRepository.insertSelective(aftersale);
    }

    @Override
    public LitemallAftersale findById(Integer userId, Integer id) {
        LitemallAftersaleExample example = new LitemallAftersaleExample();
        example.or().andIdEqualTo(id).andUserIdEqualTo(userId).andDeletedEqualTo(false);
        return litemallAftersaleRepository.selectOneByExample(example);
    }

    @Override
    public void updateById(LitemallAftersale aftersale) {
        aftersale.setUpdateTime(ZonedDateTime.now());
        litemallAftersaleRepository.updateByPrimaryKeySelective(aftersale);
    }


    private String getPageOrderBy(Pageable page) {
        if(page!= null && page.getSort() != null) {
            StringBuilder sb = new StringBuilder();
            page.getSort().forEach(sort -> sb.append(sort.getProperty())
            .append(" ").append(sort.getDirection()).append(","));
            if(sb.length() > 1) {
                return (sb.substring(0,sb.length()-1));
             }
        }
        return null;
    }
}
